﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;
using TSites.Administrator.Models;
using TSites.Common.Const;
using TSites.Common.Enums;
using TSites.Core.Domain.UserMangerment;
using TSites.UserMgmt;

namespace TSites.Administrator.Controllers
{
    public class LogonController : Controller
    {
		public IAdminMembership AdminMembershipService { get; set; }
        public IAdminSession AdminSessionService { get; set; }
		
        [HttpGet]
        public ActionResult Index()
        {
			return View();
        }

		[HttpPost]
		[ValidateAntiForgeryToken(Salt="LogonPost")]
		public ActionResult Index(LogonViewModel logon)
		{
			// validate captcha
			string captcha;
			object captchaSession = Session[StringConst.CAPTCHA];
			if (captchaSession == null || (captcha = captchaSession.ToString()) != logon.Captcha)
			{
				ModelState.AddModelError("Captcha", "Wrong value, please try again.");
				return View(logon);
			}
			// clear captchar session
			Session.Remove(StringConst.CAPTCHA);

			if (ModelState.IsValid)
			{
				User currentUser;
				string errorMsg = string.Empty, key = string.Empty;
				RET_CODE retCode = AdminMembershipService.ValidateUser(logon.Username, logon.Password, out currentUser);
				switch (retCode)
				{
					case RET_CODE.SUCCESS:
					case RET_CODE.MUST_CHANGE_PASSWORD:
						// save User in Session
                        AdminSessionService.Add2Session(currentUser);
						if (logon.RememberMe)
						{
							System.Web.Security.FormsAuthentication.SetAuthCookie(logon.Username, true);
						}

						if (retCode == RET_CODE.SUCCESS)
						{
							return RedirectToAction("Index", "Home");
						}
						else
						{
							return RedirectToAction("ChangePassword", "UserManagement");
						}

					case RET_CODE.DB_ERROR:
						errorMsg = "DB error";
						break;

					case RET_CODE.NOT_YET_ACTIVED:
						key = "Username";
						errorMsg = "User is not actived";
						break;

					case RET_CODE.USER_LOCKED:
						key = "Username";
						errorMsg = "User is locked";
						break;

					case RET_CODE.USERID_DOES_NOT_EXISTED:
						key = "Username";
						errorMsg = "User doesn't exist";
						break;

					case RET_CODE.WRONG_PASSWORD:
						key = "Password";
						errorMsg = "Wrong password";
						break;
					
					default:
						errorMsg = "Undefine error";
						break;
				}
				ModelState.AddModelError("Username", errorMsg);
			}
			return View("Index");
		}

		public ActionResult Logout()
		{
			Session.Clear();
			Session.Abandon();
			return RedirectToAction("Index");
		}

		#region Captchar
		
		public ActionResult CaptchaImage()
		{
			return View();
		}

		public ActionResult GenerateCaptchaImage()
		{
 			string captcha;
			Bitmap bitmap = AdminMembershipService.GenerateCaptcha(out captcha);
			// image stream
			FileContentResult captchaImg = null;
			using (MemoryStream mStream = new MemoryStream())
			{
				bitmap.Save(mStream, ImageFormat.Jpeg);
				captchaImg = this.File(mStream.GetBuffer(), "image/jpeg");
			}
			bitmap.Dispose();
			
			// save the Captcha Hash in the Session
			Session[StringConst.CAPTCHA] = captcha;

			// return the Captcha Image
			return captchaImg;
		}

		#endregion
	}
}
